package com.example.sunmiv1.activity.good;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.example.sunmiv1.R;
import com.example.sunmiv1.adapter.GoodsManageAdapter;
import com.example.sunmiv1.adapter.MemberTimeAdapter;
import com.example.sunmiv1.adapter.good.GoodSortAdapter;
import com.example.sunmiv1.base.BaseActivity;
import com.example.sunmiv1.base.bean;
import com.example.sunmiv1.dialog.BaseDialog;
import com.example.sunmiv1.dialog.DeleteGoodDialog;
import com.example.sunmiv1.dialog.good.BatchSettingDialog;
import com.example.sunmiv1.dialog.good.GoodSettingDialog;
import com.example.sunmiv1.entity.LoginEntity;
import com.example.sunmiv1.entity.NewGoodsClassInfo;
import com.example.sunmiv1.entity.NewGoodsListBean;
import com.example.sunmiv1.entity.SellcountBean;
import com.example.sunmiv1.entity.good.NewGoodInfo;
import com.example.sunmiv1.utils.Tools;
import com.example.sunmiv1.utils.net.ACache;
import com.example.sunmiv1.utils.net.Common;
import com.example.sunmiv1.utils.net.GsonUtils;
import com.example.sunmiv1.utils.net.HttpUtils;
import com.example.sunmiv1.utils.net.LoadingDialog;
import com.example.sunmiv1.utils.net.TextCallBack;
import com.example.sunmiv1.utils.zxing.Constant;
import com.example.sunmiv1.views.RecyclerViewNoScrollUtil;
import com.example.sunmiv1.vm.GoodsMangerViewModel;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.JustifyContent;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class GoodsManageActivity extends BaseActivity {


    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.title_title)
    TextView titleTitle;
    @BindView(R.id.goodsManage_search)
    TextView goodsManageSearch;
    @BindView(R.id.goodsManage_edit)
    EditText goodsManageEdit;
    @BindView(R.id.goodsManage_screen)
    LinearLayout goodsManageScreen;
    @BindView(R.id.goodsManage_listView)
    PullToRefreshListView goodsManageListView;
    @BindView(R.id.goodsManage_checkAll)
    CheckBox goodsManageCheckAll;
    @BindView(R.id.goodsManage_selected)
    TextView goodsManageSelected;
    @BindView(R.id.goodsManage_tip)
    TextView goodsManageTip;
    @BindView(R.id.goodsManage_batch)
    TextView goodsManageBatch;
    @BindView(R.id.goodsManage_addGood)
    TextView goodsManageAddGood;
    @BindView(R.id.goodsManage_sort)
    GridView goodsManageSort;
    @BindView(R.id.goodsManage_metering)
    GridView goodsManageMetering;
    @BindView(R.id.goodsManage_type)
    GridView goodsManageType;
    @BindView(R.id.goodsManage_goodStatus)
    Spinner goodsManageGoodStatus;
    @BindView(R.id.goodsManage_goodSku)
    Spinner goodsManageGoodSku;
    @BindView(R.id.goodsManage_classList1)
    Spinner goodsManageClassList1;
    @BindView(R.id.goodsManage_classList2)
    Spinner goodsManageClassList2;
    @BindView(R.id.goodsManage_classList3)
    Spinner goodsManageClassList3;
    @BindView(R.id.goodsManage_screenDialog1)
    LinearLayout goodsManageScreenDialog1;
    @BindView(R.id.goodsManage_screenDialog)
    LinearLayout goodsManageScreenDialog;
    @BindView(R.id.goodsManage_searchType)
    Spinner goodsManageSearchType;
    @BindView(R.id.goodsManage_clear)
    TextView goodsManageClear;
    @BindView(R.id.goodsManage_confirm)
    TextView goodsManageConfirm;
    @BindView(R.id.scan_storeGoodsManager)
    ImageView scanStoreGoodsManager;

    private boolean statsFlag = false;
    private boolean skuFlag = false;

    private int page = 1;
    private ACache aCache;
    private Context context;
    private LoadingDialog loadingDialog;
    private NewGoodsListBean newGoodsListBean;
    private List<NewGoodsListBean.DataBean> list = new ArrayList<>();
    private GoodsManageAdapter manageAdapter;
    private Intent intent;

    private List<String> goodStatus = new ArrayList<>();
    private List<String> goodSku = new ArrayList<>();

    /**
     * 搜索類型
     */
    private List<String> searchType = new ArrayList<>();
    private int searchTypeFlag = 1;
    private int size = 0;//已選中的商品數量
    private int status = -1;//0正常 1下架 2刪除
    private int attribute_state = 0;//1無規格 2規格


    private int oneIndex = 0, twoIndex = 0, threeIndex = 0;//選擇的分類的下標
    private NewGoodsClassInfo newGoodsClassInfo;
    private int classType = 0;
    private List<NewGoodsClassInfo.DataBean> oneList = new ArrayList<>();
    private List<NewGoodsClassInfo.DataBean> twoList = new ArrayList<>();
    private List<NewGoodsClassInfo.DataBean> threeList = new ArrayList<>();


    private ArrayList<String> goodsId = new ArrayList<>();

    private GoodSortAdapter sortAdapter;
    private List<String> sortList = new ArrayList<>();
    private int sortIndex = 99;

    private GoodSortAdapter meteringAdapter;
    private List<String> meteringList = new ArrayList<>();
    private int pricing_method = 0;//是否稱重計價 1不稱重 2稱重

    private GoodSortAdapter typeAdapter;
    private List<String> typeList = new ArrayList<>();
    private int advance_sale_status = -1;//商城預售 0現貨預售 1預售模式
    public static SellcountBean sellcountBean;

    private GoodsMangerViewModel mViewModel;

    public static void intent(SellcountBean sellcountBean1,Context context){
        sellcountBean=sellcountBean1;
        Intent intent=new Intent(context,GoodsManageActivity.class);
        context.startActivity(intent);
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    list.addAll(newGoodsListBean.getData());
                    if (goodsManageCheckAll.isChecked()){
                        for (NewGoodsListBean.DataBean dataBean:list) {
                            dataBean.setCheck(true);
                        }
                        goodsManageSelected.setText("已選" + list.size() + "件");
                    }
                case 2:
                    setManageAdapter();
                    break;
                case 3:
                    if (classType == 0) {
                        oneList.add(new NewGoodsClassInfo.DataBean("0", "一級分類"));
                        oneList.addAll(newGoodsClassInfo.getData());
                        setClass1Adapter();
                    } else if (classType == 1) {
                        if (newGoodsClassInfo.getData().size() > 0) {
                            goodsManageClassList2.setVisibility(View.VISIBLE);
                        }
                        twoList.add(new NewGoodsClassInfo.DataBean("0", "二級分類"));
                        twoList.addAll(newGoodsClassInfo.getData());
                        setClass2Adapter();
                    } else if (classType == 2) {
                        if (newGoodsClassInfo.getData().size() > 0) {
                            goodsManageClassList3.setVisibility(View.VISIBLE);
                        }
                        threeList.add(new NewGoodsClassInfo.DataBean("0", "三級分類"));
                        threeList.addAll(newGoodsClassInfo.getData());
                        setClass3Adapter();
                    }
                    break;
                case 4:
                    break;
            }
        }
    };

    @Override
    protected void initView() {
        setContentView(R.layout.activity_goods_manage);
        ButterKnife.bind(this);
        mViewModel=new GoodsMangerViewModel(this);
        mViewModel.init();
        titleTitle.setText("商品管理");
        context = this;
        aCache = ACache.get(context);
        loadingDialog = new LoadingDialog(context);
    }

    @Override
    protected void initData() {
        searchType.add("貨號");
        searchType.add("條碼");
        searchType.add("名稱");
        setSearchTypeAdapter();
        goodStatus.add("商品狀態");
        goodStatus.add("上架");
        goodStatus.add("下架");
        setGoodStatus();
        goodSku.add("商品規格");
        goodSku.add("單規格");
        goodSku.add("多規格");
        setGoodSku();
        sortList.add("添加時間升序");
        sortList.add("貨號升序");
        sortList.add("商品名稱升序");
        sortList.add("添加時間降序");
        sortList.add("貨號降序");
        sortList.add("商品名稱降序");
        setSortAdapter();
        meteringList.add("所有類型");
        meteringList.add("非稱重商品");
        meteringList.add("稱重商品");
        setMeteringAdapter();
        typeList.add("所有類型");
        typeList.add("現貨銷售");
        typeList.add("預售模式");
        setTypeAdapter();
//        getGoods();
        getClassList("");
        if (sellcountBean!=null&&(!"1".equals(sellcountBean.getJurisdiction().getAddgoods())||!"1".equals(sellcountBean.getJurisdiction().getShowpurch_price()))) {
            goodsManageAddGood.setVisibility(View.GONE);
        }else {
            if ("3".equals(aCache.getAsString("userType"))){
                LoginEntity loginEntity= GsonUtils.JsonToBean(aCache.getAsString("loginInfo"), LoginEntity.class);
                if (loginEntity.getData().getAuth().getAdd_goods_jurisdiction()!=1){
                    goodsManageAddGood.setVisibility(View.GONE);
                }else {
                    goodsManageAddGood.setVisibility(View.VISIBLE);
                }
            }else {
                goodsManageAddGood.setVisibility(View.VISIBLE);
            }
        }

//        if (!"1".equals(sellcountBean.getJurisdiction().getBatch_delgoods())) {
//            goodsManageAddGood.setVisibility(View.GONE);
//        }else {
//        }

        if ("3".equals(aCache.getAsString("userType"))) {
            LoginEntity loginEntity = GsonUtils.JsonToBean(aCache.getAsString("loginInfo"), LoginEntity.class);
            if (loginEntity.getData().getAuth().getGoods_manage_operate() != 1) {
                goodsManageBatch.setVisibility(View.GONE);
            } else {
                goodsManageBatch.setVisibility(View.VISIBLE);
            }
        } else {
            goodsManageBatch.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void initListener() {
        goodsManageListView.setMode(PullToRefreshBase.Mode.BOTH);
        goodsManageListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                initList();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                getGoods();
            }
        });

        goodsManageGoodStatus.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (!statsFlag) {
                    statsFlag = true;
                    return;
                }
                status = position - 1;
                initList();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        goodsManageGoodSku.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (!skuFlag) {
                    skuFlag = true;
                    return;
                }
                attribute_state = position;
                initList();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        goodsManageClassList1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position != 0) {
                    classType = 1;
                    oneIndex = position;
                    twoIndex = 0;
                    twoList.clear();
                    goodsManageClassList2.setVisibility(View.INVISIBLE);
                    threeIndex = 0;
                    threeList.clear();
                    goodsManageClassList3.setVisibility(View.INVISIBLE);
                    getClassList(oneList.get(position).getId());
                } else {
                    twoIndex = 0;
                    twoList.clear();
                    goodsManageClassList2.setVisibility(View.INVISIBLE);
                    threeIndex = 0;
                    threeList.clear();
                    goodsManageClassList3.setVisibility(View.INVISIBLE);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        goodsManageClassList2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position != 0) {
                    twoIndex = position;
                    classType = 2;
                    threeIndex = 0;
                    threeList.clear();
                    goodsManageClassList3.setVisibility(View.INVISIBLE);
                    getClassList(twoList.get(position).getId());
                } else {
                    threeIndex = 0;
                    threeList.clear();
                    goodsManageClassList3.setVisibility(View.INVISIBLE);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        goodsManageClassList3.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                threeIndex = position;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        goodsManageCheckAll.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (adapterType!=0){
                size=0;
                for (NewGoodsListBean.DataBean bean : list) {
                    if (isChecked) {
                        if (size < 200) {
                            size++;
                            bean.setCheck(true);
                            goodsId.add(bean.getId());
                        }
                    } else {
                        bean.setCheck(false);
                        if (goodsId.indexOf(bean.getId()) != -1) {
                            goodsId.remove(goodsId.indexOf(bean.getId()));
                        }
                    }
                }
                if (isChecked) {
                    goodsManageSelected.setText("已選" + size + "件");
                } else {
                    goodsManageSelected.setText("已選" + 0 + "件");
                }
            }else {
                adapterType=-1;
            }
            setManageAdapter();
        });

        goodsManageSearchType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                searchTypeFlag = position + 1;
                switch (position) {
                    case 0:
                        goodsManageEdit.setHint("請輸入商品貨號");
                        scanStoreGoodsManager.setVisibility(View.VISIBLE);
                        break;
                    case 1:
                        goodsManageEdit.setHint("請輸入商品條碼");
                        scanStoreGoodsManager.setVisibility(View.VISIBLE);
                        break;
                    case 2:
                        goodsManageEdit.setHint("請輸入商品名稱");
                        scanStoreGoodsManager.setVisibility(View.GONE);
                        break;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        goodsManageSort.setOnItemClickListener((parent, view, position, id) -> {
            sortAdapter.setSelect(position);
            sortIndex = position;
        });
        goodsManageMetering.setOnItemClickListener((parent, view, position, id) -> {
            meteringAdapter.setSelect(position);
            pricing_method = position;
        });
        goodsManageType.setOnItemClickListener((parent, view, position, id) -> {
            typeAdapter.setSelect(position);
            advance_sale_status = position - 1;
        });
    }

    private void setSearchTypeAdapter() {
        ArrayAdapter arrayAdapter = new ArrayAdapter(context, R.layout.item_select, searchType);
        arrayAdapter.setDropDownViewResource(R.layout.item_drop);
        goodsManageSearchType.setAdapter(arrayAdapter);
    }

    private void setGoodStatus() {
        //往會員來源Spinner中添加數據
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, R.layout.spinner_item, goodStatus);  //創建一個數組適配器
        adapter.setDropDownViewResource(R.layout.dropdown_stytle);
        goodsManageGoodStatus.setAdapter(adapter);
    }

    /**
     * 規格篩選適配器
     */
    private void setGoodSku() {
        //往會員來源Spinner中添加數據
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, R.layout.spinner_item, goodSku);  //創建一個數組適配器
        adapter.setDropDownViewResource(R.layout.dropdown_stytle);
        goodsManageGoodSku.setAdapter(adapter);
    }

    private void setSortAdapter() {
        sortAdapter = new GoodSortAdapter(sortList);
        goodsManageSort.setAdapter(sortAdapter);
    }

    private void setMeteringAdapter() {
        meteringAdapter = new GoodSortAdapter(meteringList);
        goodsManageMetering.setAdapter(meteringAdapter);
    }

    private void setTypeAdapter() {
        typeAdapter = new GoodSortAdapter(typeList);
        goodsManageType.setAdapter(typeAdapter);
    }

    private int adapterType=-1;
    private void setManageAdapter() {
        if (manageAdapter == null) {
            manageAdapter = new GoodsManageAdapter(list,mViewModel,sellcountBean,aCache);
            manageAdapter.setEntityList(mViewModel.getList());
            goodsManageListView.setAdapter(manageAdapter);
        } else {
            manageAdapter.setEntityList(mViewModel.getList());
            manageAdapter.notifyDataSetChanged();
        }
        manageAdapter.setOperation((type, index) -> {
            ArrayList<String> list1 = new ArrayList<>();
            list1.add(list.get(index).getId());
            switch (type) {
                case 0:
                    size=0;
                    adapterType=type;
                    for (int i=0;i<list.size();i++){
                        if (list.get(i).isCheck()) {
                            size++;
                            goodsId.add(list.get(i).getId());
                        }
//                        else {
//                            size--;
//                            if (goodsId.indexOf(list.get(i).getId()) != -1) {
//                                goodsId.remove(goodsId.indexOf(list.get(i).getId()));
//                            }
//                        }
                    }
                    goodsManageSelected.setText("已選" + size + "件");
                    goodsManageCheckAll.setChecked(false);
                    break;
                case 1:
                    getGoodInfo(list.get(index).getId(),list.get(index).getCate_name());
                    break;
                case 2://上下架
                    if ("0".equals(list.get(index).getStatus())) {
                        batchSetting(index, 1);
                    } else {
                        batchSetting(index, 0);
                    }
                    break;
                case 3://刪除
                    DeleteGoodDialog dialog=DeleteGoodDialog.newInstance();
                    dialog.setSubmit("確認");
                    dialog.callback(o -> delGood(list1))
                            .startShow(getSupportFragmentManager(), "")
                            .setCancelable(false);
                    break;
                default:
                    break;
            }
        });
    }

    private void setClass1Adapter() {
        ArrayAdapter arrayAdapter = new ArrayAdapter(context, R.layout.item_select, oneList) {
            @Override
            public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                @SuppressLint("ViewHolder") View view = ((Activity) context).getLayoutInflater().inflate(R.layout.item_drop, parent, false);
                final TextView text = view.findViewById(R.id.drop_view);
                text.setText(oneList.get(position).getClass_name());
                return view;
            }

            @NonNull
            @Override
            public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                View view = ((Activity) context).getLayoutInflater().inflate(R.layout.item_select, parent, false);
                final TextView text = view.findViewById(R.id.spinner_tv);
                text.setText(oneList.get(position).getClass_name());
                return view;
            }
        };
        goodsManageClassList1.setAdapter(arrayAdapter);
    }

    private void setClass2Adapter() {
        ArrayAdapter arrayAdapter = new ArrayAdapter(context, R.layout.item_select, twoList) {
            @Override
            public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                @SuppressLint("ViewHolder") View view = ((Activity) context).getLayoutInflater().inflate(R.layout.item_drop, parent, false);
                final TextView text = view.findViewById(R.id.drop_view);
                text.setText(twoList.get(position).getClass_name());
                return view;
            }

            @NonNull
            @Override
            public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                View view = ((Activity) context).getLayoutInflater().inflate(R.layout.item_select, parent, false);
                final TextView text = view.findViewById(R.id.spinner_tv);
                text.setText(twoList.get(position).getClass_name());
                return view;
            }
        };
        goodsManageClassList2.setAdapter(arrayAdapter);
    }

    private void setClass3Adapter() {
        ArrayAdapter arrayAdapter = new ArrayAdapter(context, R.layout.item_select, threeList) {
            @Override
            public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                @SuppressLint("ViewHolder") View view = ((Activity) context).getLayoutInflater().inflate(R.layout.item_drop, parent, false);
                final TextView text = view.findViewById(R.id.drop_view);
                text.setText(threeList.get(position).getClass_name());
                return view;
            }

            @NonNull
            @Override
            public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                View view = ((Activity) context).getLayoutInflater().inflate(R.layout.item_select, parent, false);
                final TextView text = view.findViewById(R.id.spinner_tv);
                text.setText(threeList.get(position).getClass_name());
                return view;
            }
        };
        goodsManageClassList3.setAdapter(arrayAdapter);
    }


    @OnClick({R.id.title_back, R.id.goodsManage_search, R.id.goodsManage_screen, R.id.goodsManage_batch, R.id.goodsManage_addGood,
            R.id.goodsManage_screenDialog, R.id.goodsManage_screenDialog1,
            R.id.goodsManage_clear, R.id.goodsManage_confirm,R.id.scan_storeGoodsManager})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.goodsManage_search:
                initList();
                break;
            case R.id.goodsManage_screen:
                goodsManageScreenDialog.setVisibility(View.VISIBLE);
                break;
            case R.id.goodsManage_batch:
                if (goodsId.size() == 0) {
                    Toast.makeText(context, "請先選擇商品", Toast.LENGTH_SHORT).show();
                    return;
                }
                BatchSettingDialog.newInstance(goodsId,sellcountBean,Integer.parseInt(aCache.getAsString("userType")))
                        .callback(o -> {
                            if ("9".equals(o)) {
                                DeleteGoodDialog.newInstance()
                                        .callback(o1 -> delGood(goodsId))
                                        .startShow(getSupportFragmentManager(), "")
                                        .setCancelable(false);
                            } else {
                                GoodSettingDialog.newInstance(Integer.parseInt((String) o), goodsId)
                                        .startShow(getSupportFragmentManager(), "")
                                        .callback(o1 -> {
                                            initList();
                                        })
                                        .setCancelable(false);
                            }
                        })
                        .startShow(getSupportFragmentManager(), "")
                        .setCancelable(false);
                break;
            case R.id.goodsManage_addGood:
                intent = new Intent(context, NewAddGoodActivity.class);
                startActivity(intent);
                break;
            case R.id.goodsManage_screenDialog:
                break;
            case R.id.goodsManage_screenDialog1:
                break;
            case R.id.goodsManage_clear:
//                goodsManageScreenDialog.setVisibility(View.GONE);
                oneIndex = 0;
                goodsManageClassList1.setSelection(0);
                goodsManageClassList2.setVisibility(View.INVISIBLE);
                goodsManageClassList3.setVisibility(View.INVISIBLE);

                sortAdapter.setSelect(0);
                meteringAdapter.setSelect(0);
                typeAdapter.setSelect(0);

                twoIndex = 0;
                threeIndex = 0;
                pricing_method = 0;
                advance_sale_status = -1;
//                initList();
                break;
            case R.id.goodsManage_confirm:
                goodsManageScreenDialog.setVisibility(View.GONE);
                initList();
                break;
            case R.id.scan_storeGoodsManager:
                startQrCode();
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case Constant.REQ_PERM_CAMERA:
                // 攝像頭權限申請
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 獲得授權
                    startQrCode();
                } else {
                    // 被禁止授權
                    Toast.makeText(context, "請至權限中心打開本應用的相機訪問權限", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode != 1 && requestCode == Constant.REQ_QR_CODE && resultCode == RESULT_OK) {//掃描結果回調
            Bundle bundle = data.getExtras();
            goodsManageEdit.setText(bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN));
//            getGoods();
        }
    }

    private void initList() {
        size = 0;
        goodsManageSelected.setText("已選" + size + "件");
        goodsManageCheckAll.setChecked(false);
        goodsId.clear();
        page = 1;
        list.clear();
        setManageAdapter();
        getGoods();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initList();
    }

    /**
     * 獲取商品列表
     */
    private void getGoods() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
//            if ("1".equals(aCache.getAsString("userType")) || "2".equals(aCache.getAsString("userType"))) {
            if ("1".equals(aCache.getAsString("userType"))) {
                jsonObject.put("managerType", 3);//3商戶 4門店
            } else {
                jsonObject.put("managerType", 4);//3商戶 4門店
            }
//            }
            jsonObject.put("user_type", aCache.getAsString("userType"));//1商戶 2店長 3收銀員
            jsonObject.put("page", page);
            jsonObject.put("limit", 10);
            if (oneIndex != 0) {
                jsonObject.put("person1", oneList.get(oneIndex).getId());//一級分類
            }
            if (twoIndex != 0) {
                jsonObject.put("person2", twoList.get(twoIndex).getId());//二級分類
            }
            if (threeIndex != 0) {
                jsonObject.put("person3", threeList.get(threeIndex).getId());//三級分類
            }
            jsonObject.put("keyword", goodsManageEdit.getText().toString().trim());
            jsonObject.put("need_img", "");//是否需要圖片
            jsonObject.put("need_goods_num", "");//是否需要庫存
            jsonObject.put("need_count", "");//是否需要總數量
            jsonObject.put("keyword_type", searchTypeFlag);//關鍵詞搜索類型 1貨號 2條碼 3名稱
            jsonObject.put("order_type", "");//1升序 2降序
            switch (sortIndex) {
                case 0:
                    jsonObject.put("condition_name", "1");//排序規則關鍵字
                    jsonObject.put("order_type", "1");//排序規則關鍵字
                    break;
                case 3:
                    jsonObject.put("condition_name", "1");//排序規則關鍵字
                    jsonObject.put("order_type", "2");//排序規則關鍵字
                    break;
                case 1:
                    jsonObject.put("condition_name", "2");//排序規則關鍵字
                    jsonObject.put("order_type", "1");//排序規則關鍵字
                    break;
                case 4:
                    jsonObject.put("condition_name", "2");//排序規則關鍵字
                    jsonObject.put("order_type", "2");//排序規則關鍵字
                    break;
                case 2:
                    jsonObject.put("condition_name", "4");//排序規則關鍵字
                    jsonObject.put("order_type", "1");//排序規則關鍵字
                    break;
                case 5:
                    jsonObject.put("condition_name", "4");//排序規則關鍵字
                    jsonObject.put("order_type", "2");//排序規則關鍵字
                    break;
            }
            jsonObject.put("recovery_type", 2);//回收站
            jsonObject.put("attribute_state", attribute_state);//規格 1無規格 2規格
            jsonObject.put("pricing_method", pricing_method);//是否稱重計價 1不稱重 2稱重
            jsonObject.put("online_state", "");//是否在商城中出售 0不在 1在
            if (status >= 0) {
                jsonObject.put("status", status);//狀態 0正常 1下架 2刪除
            }
            if (advance_sale_status >= 0) {
                jsonObject.put("advance_sale_status", advance_sale_status);//商城預售 0現貨預售 1預售模式
            }
            jsonObject = Tools.createParameterCode(jsonObject);
            HttpUtils.post(context, Common.GET_GOODS_LIST, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    page++;
                    loadingDialog.dismiss();
                    goodsManageListView.onRefreshComplete();
                    newGoodsListBean = GsonUtils.JsonToBean(text, NewGoodsListBean.class);
                    if (newGoodsListBean.getStatus() == 1) {
                        handler.sendEmptyMessage(1);
                    } else {
                        handler.sendEmptyMessage(2);
                    }
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                    goodsManageListView.onRefreshComplete();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 獲取商品分類
     */
    private void getClassList(String id) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("pid", id);
            jsonObject = Tools.createParameterCode(jsonObject);
            HttpUtils.post(context, Common.GET_GOODS_CLASS_LIST, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    try {
                        JSONObject json = new JSONObject(text);
                        Message msg = new Message();
                        if (json.getInt("status") == 1) {
                            newGoodsClassInfo = GsonUtils.JsonToBean(text, NewGoodsClassInfo.class);
                            msg.what = 3;
                        } else {
                            msg.what = 4;
                        }
                        handler.sendMessage(msg);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                protected void onFailure(ResponseException e) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private NewGoodInfo newGoodInfo;


    /**
     * 獲取商品詳情
     */
    private void getGoodInfo(final String goodId,final String className) {
        JSONObject jSONObject = new JSONObject();
        try {
//            if ("1".equals(this.aCache.getAsString("userType")) || "2".equals(this.aCache.getAsString("userType"))) {
            boolean bool = "1".equals(this.aCache.getAsString("userType"));
            if (bool) {
                jSONObject.put("managerType", 3);
            } else {
                jSONObject.put("managerType", 4);
            }
//            }
            jSONObject.put("goods_id", goodId);
            HttpUtils.post(context, Common.GET_GOOD_INFO, Tools.createParameterCode(jSONObject), new TextCallBack() {
                @Override
                protected void onFailure(ResponseException param1ResponseException) {
                }

                @Override
                protected void onSuccess(String text) {
                    try {
                        if ((new JSONObject(text)).getInt("status") == 1) {
                            newGoodInfo = new Gson().fromJson(text, NewGoodInfo.class);
                            intent = new Intent(context, NewAddGoodActivity.class);
                            intent.putExtra("info", GoodsManageActivity.this.newGoodInfo.getData());
                            intent.putExtra("goodId", goodId);
                            intent.putExtra("className",className);
                            startActivity(intent);
                        }
                        return;
                    } catch (JSONException param1String) {
                        param1String.printStackTrace();
                        return;
                    }
                }
            });
            return;
        } catch (JSONException paramString) {
            paramString.printStackTrace();
            return;
        }
    }


    /**
     * 批量操作
     */
    private void batchSetting(int index, int type) {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("user_type", aCache.getAsString("userType"));
            jsonObject.put("goodsIds", new JSONArray().put(list.get(index).getId()));
//            if ("1".equals(aCache.getAsString("userType")) || "2".equals(aCache.getAsString("userType"))) {
            boolean bool = "1".equals(this.aCache.getAsString("userType"));
            if (bool) {
                jsonObject.put("managerType", 3);
            } else {
                jsonObject.put("managerType", 4);
            }
//            }
            jsonObject.put("key","status");
            jsonObject.put("value", type);
            if ("1".equals(aCache.getAsString("userType")) || "2".equals(aCache.getAsString("userType"))) {
                jsonObject.put("operator_id", aCache.getAsString("operator_id"));
            } else {
                jsonObject.put("operator_id", aCache.getAsString("uid"));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        HttpUtils.post(context, Common.BATCH_OPERATE_GOODS, Tools.createParameterCode(jsonObject), new TextCallBack() {
            @Override
            protected void onSuccess(String text) {
                loadingDialog.dismiss();
                try {
                    JSONObject json = new JSONObject(text);
                    Toast.makeText(context, json.getString("message"), Toast.LENGTH_SHORT).show();
                    if (json.getInt("status") == 1) {
                        list.get(index).setStatus(type + "");
                        setManageAdapter();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected void onFailure(ResponseException e) {
                loadingDialog.dismiss();
            }
        });

    }

    /**
     * 刪除商品
     */
    private void delGood(List<String> l) {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("user_type", aCache.getAsString("userType"));
            Gson gson=new Gson();
            jsonObject.put("ids",gson.toJson(l));
//            if ("1".equals(aCache.getAsString("userType")) || "2".equals(aCache.getAsString("userType"))) {
            boolean bool = "1".equals(this.aCache.getAsString("userType"));
            if (bool) {
                jsonObject.put("managerType", 3);
            } else {
                jsonObject.put("managerType", 4);
            }
//            }
            if ("1".equals(aCache.getAsString("userType")) || "2".equals(aCache.getAsString("userType"))) {
                jsonObject.put("operator_id", aCache.getAsString("operator_id"));
            } else {
                jsonObject.put("operator_id", aCache.getAsString("uid"));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        HttpUtils.post(context, Common.DEL_GOODS_INFO, Tools.createParameterCode(jsonObject), new TextCallBack() {
            @Override
            protected void onSuccess(String text) {
                loadingDialog.dismiss();
                try {
                    JSONObject json = new JSONObject(text);
                    Toast.makeText(context, json.getString("msg"), Toast.LENGTH_SHORT).show();
                    if (json.getInt("status") == 1) {
                        initList();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected void onFailure(ResponseException e) {
                loadingDialog.dismiss();
            }
        });

    }
}
